/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa036is.controllers;

import cz.muni.fi.pa036is.dto.AdmissionFormTO;
import cz.muni.fi.pa036is.dto.AdmissionGridTO;
import cz.muni.fi.pa036is.dto.MatchDetailTO;
import cz.muni.fi.pa036is.dto.PersonDetailTO;
import cz.muni.fi.pa036is.dto.RoundFormTO;
import cz.muni.fi.pa036is.dtoconverters.MatchConverter;
import cz.muni.fi.pa036is.servicesinterface.MatchService;
import cz.muni.fi.pa036is.servicesinterface.PersonService;
import cz.muni.fi.pa036is.servicesinterface.RoundService;
import cz.muni.fi.pa036is.validators.RoundValidator;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 *
 * @author jostri
 */
@Controller
@SessionAttributes("round")
public class RoundController {

    @Autowired
    private RoundService roundService;
    @Autowired
    private MatchService matchService;
    @Autowired
    private PersonService personService;

    @RequestMapping(value = "/admin/round/edit", params = {"matchId", "seqNum"})
    public String edit(@RequestParam("matchId") Long matchId, @RequestParam("seqNum") int seqId, ModelMap model) {

        RoundFormTO round = round = this.roundService.getRoundForm(matchId, seqId);

        if (round != null && round.getMatch() == null) {
            MatchDetailTO match = this.matchService.getMatchDetail(matchId);
            round.setMatch(MatchConverter.convertToMatchBasicTO(match));
        }

        model.addAttribute("round", round);
        model.addAttribute("player1", this.personService.getPersonDetail(round.getMatch().getPlayer1Id()));
        model.addAttribute("player2", this.personService.getPersonDetail(round.getMatch().getPlayer2Id()));

        return "/admin/round/edit";
    }

    @RequestMapping(value = "/admin/round/edit", method = RequestMethod.POST)
    public String edit(@Validated @ModelAttribute("round") RoundFormTO round, BindingResult result, ModelMap model,
            HttpSession session) {

        RoundValidator roundValidator = new RoundValidator();
        roundValidator.validate(round, result);
        
        if (result.hasErrors()) {
            
            HashMap<String, String> errors = new HashMap<String, String>();
            for (FieldError error : result.getFieldErrors()) {
                errors.put(error.getField(), error.getDefaultMessage());
            }
            model.put("errors", errors);
            for (ObjectError o : result.getAllErrors()) {
                System.err.println(o);
            }
            
            model.addAttribute("player1", this.personService.getPersonDetail(round.getMatch().getPlayer1Id()));
            model.addAttribute("player2", this.personService.getPersonDetail(round.getMatch().getPlayer2Id()));
            
            model.put("round", round);
            return "/admin/round/edit";
//            return "/admin/round/edit?matchId=" + round.getMatch().getId() + "&seqNum=" + round.getSequenceNumber();
        }

        if (round.getSequenceNumber() < 0) {
            this.roundService.addRound(round);
        } else {
            this.roundService.editRound(round);
        }


        return "redirect:/admin/match/detail?id=" + round.getMatch().getId();
    }

    @RequestMapping(value = "/admin/round/add", params = {"matchId"})
    public String add(@RequestParam("matchId") Long matchId, ModelMap model) {

        RoundFormTO round = new RoundFormTO();
        round.setMatch(this.matchService.getMatchBasic(matchId));
        round.setSequenceNumber(this.roundService.getNextRoundIndexForMatch(matchId));

        model.addAttribute("round", round);
        model.addAttribute("player1", this.personService.getPersonDetail(round.getMatch().getPlayer1Id()));
        model.addAttribute("player2", this.personService.getPersonDetail(round.getMatch().getPlayer2Id()));

        return "/admin/round/add";
    }

    @RequestMapping(value = "/admin/round/add", method = RequestMethod.POST)
    public String add(@Validated @ModelAttribute("round") RoundFormTO round, BindingResult result, ModelMap model,
            HttpSession session) {

        RoundValidator roundValidator = new RoundValidator();
        roundValidator.validate(round, result);
        
        if (result.hasErrors()) {
            
            HashMap<String, String> errors = new HashMap<String, String>();
            for (FieldError error : result.getFieldErrors()) {
                errors.put(error.getField(), error.getDefaultMessage());
            }
            model.put("errors", errors);
            for (ObjectError o : result.getAllErrors()) {
                System.err.println(o);
            }
            
            model.addAttribute("player1", this.personService.getPersonDetail(round.getMatch().getPlayer1Id()));
            model.addAttribute("player2", this.personService.getPersonDetail(round.getMatch().getPlayer2Id()));
            
            model.put("round", round);
            return "/admin/round/add";
        }

        this.roundService.addRound(round);
        return "redirect:/admin/match/detail?id=" + round.getMatch().getId();
    }

    @RequestMapping(value = "/admin/round/remove", params = {"matchId", "seqNum"})
    public String remove(@RequestParam("matchId") Long matchId, @RequestParam("seqNum") int seqNum, ModelMap model, HttpSession session) {

        this.roundService.deleteRound(matchId, seqNum);
        return "redirect:/admin/match/detail?id=" + matchId;
    }
}
